package com.o2opays.wechat.controller;

import com.o2opays.wechat.pojo.*;
import com.o2opays.wechat.service.LoginService;
import com.o2opays.wechat.tool.WeChatTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.logging.Logger;

/**
 * Created by tugou on 2017/12/2.
 */

@Controller
@RequestMapping("mrch")
public class MerChantController {
    @Autowired
    LoginService loginService;

    @RequestMapping("/index")
    public String wechatInde(ModelMap map) {
        String url = WeChatFinalValue.WECHAT_MAIN;

        url = url.replace("appId", WeChatContent.getInstance().getAppId());
        url = url.replace("url", WeChatContent.getInstance().getBaseUrl());

        map.addAttribute("baseUrl", url);
        return "wechatinit";
    }

    @RequestMapping("/login")
    public String login(String code, HttpSession session, ModelMap map) {
        WeChatOpenid content = WeChatTool.getWeChatOpenid(code);
        String openId = content.getOpenid();
        System.out.println("openId: "+openId);
        session.setAttribute("openId",openId);
        HttpResult result = loginService.login(openId);
        MerchatUserInfo info = (MerchatUserInfo) result.getData();
        if ("00000".equals(result.getCode())){
            session.setAttribute("openId",openId);
            return "card_index";
        }else {
            return "login";
        }
    }

}
